using GameConfig.item;
using GameLogic;
using TEngine;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class CursorManager : MonoBehaviour
{
    public Sprite normal, tool, seed, item;

    private Sprite currentSprite;   //存储当前鼠标图片
    public Image cursorImage;
    public RectTransform cursorCanvas;

    //建造图标跟随
    private Image buildImage;

    //鼠标检测
    private Camera mainCamera;
    private Grid currentGrid;

    private Vector3 mouseWorldPos;
    private Vector3Int mouseGridPos;

    private bool cursorEnable;
    private bool cursorPositionValid;

    private ItemTb currentItem;

    private Transform PlayerTransform => FindObjectOfType<Player>().transform;

    private void OnEnable()
    {
        GameEvent.AddEventListener<ItemTb, bool>(ILoginUI_Event.OnItemSelectedEvent, OnItemSelectedEvent);
        GameEvent.AddEventListener(ILoginUI_Event.AfterSceneLoadedEvent, OnAfterSceneLoadedEvent);
        //EventHandler.BeforeSceneUnloadEvent += OnBeforeSceneUnloadEvent;
        //EventHandler.AfterSceneLoadedEvent += OnAfterSceneLoadedEvent;
    }

    private void OnDisable()
    {
        GameEvent.RemoveEventListener<ItemTb, bool>(ILoginUI_Event.OnItemSelectedEvent, OnItemSelectedEvent);
        GameEvent.RemoveEventListener(ILoginUI_Event.AfterSceneLoadedEvent, OnAfterSceneLoadedEvent);
        //EventHandler.ItemSelectedEvent -= OnItemSelectedEvent;
        //EventHandler.BeforeSceneUnloadEvent -= OnBeforeSceneUnloadEvent;
        //EventHandler.AfterSceneLoadedEvent -= OnAfterSceneLoadedEvent;
    }



    private void Start()
    {
        //拿到建造图标
        //buildImage = cursorCanvas.GetChild(1).GetComponent<Image>();
        //buildImage.gameObject.SetActive(false);

        currentSprite = normal;
        SetCursorImage(normal);

        mainCamera = Camera.main;
    }

    private void Update()
    {
        if (cursorCanvas == null) return;

        Vector2 mousePos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(
            UIModule.UIRoot.GetComponent<RectTransform>(),
            Input.mousePosition,
            UIModule.Instance.UICamera,
            out mousePos
        );
        cursorImage.rectTransform.anchoredPosition = mousePos;

        if (!InteractWithUI() && cursorEnable)
        {
            SetCursorImage(currentSprite);
            CheckCursorValid();
            CheckPlayerInput();
        }
        else
        {
            SetCursorImage(normal);
            //buildImage.gameObject.SetActive(false);
        }
    }

    private void CheckPlayerInput()
    {
        if (Input.GetMouseButtonDown(0) && cursorPositionValid)
        {
            //执行方法
            GameEvent.Get<ILoginUI>().CallMouseClickedEvent(mouseWorldPos, currentItem);
        }
    }

    private void OnBeforeSceneUnloadEvent()
    {
        cursorEnable = false;
    }

    private void OnAfterSceneLoadedEvent()
    {
        currentGrid = FindObjectOfType<Grid>();
    }

    #region 设置鼠标样式
    /// <summary>
    /// 设置鼠标图片
    /// </summary>
    /// <param name="sprite"></param>
    private void SetCursorImage(Sprite sprite)
    {
        cursorImage.sprite = sprite;
        cursorImage.color = new Color(1, 1, 1, 1);
    }

    /// <summary>
    /// 设置鼠标可用
    /// </summary>
    private void SetCursorValid()
    {
        cursorPositionValid = true;
        cursorImage.color = new Color(1, 1, 1, 1);
        //buildImage.color = new Color(1, 1, 1, 0.5f);
    }
    /// <summary>
    /// 设置鼠标不可用
    /// </summary>
    private void SetCursorInValid()
    {
        cursorPositionValid = false;
        cursorImage.color = new Color(1, 0, 0, 0.4f);
        //buildImage.color = new Color(1, 0, 0, 0.5f);
    }
    #endregion

    /// <summary>
    /// 物品选择事件函数
    /// </summary>
    /// <param name="itemDetails"></param>
    /// <param name="isSelected"></param>
    private void OnItemSelectedEvent(ItemTb itemDetails, bool isSelected)
    {
        if (!isSelected)
        {
            currentItem = null;
            cursorEnable = false;
            currentSprite = normal;
            //buildImage.gameObject.SetActive(false);
        }
        else    //物品被选中才切换图片
        {
            currentItem = itemDetails;
            //WORKFLOW:添加所有类型对应图片
            currentSprite = itemDetails.ItemType switch
            {
                GameConfig.item.ItemType.Seed => seed,
                GameConfig.item.ItemType.Commodity => item,
                GameConfig.item.ItemType.Furniture => tool,
                GameConfig.item.ItemType.HoeTool => tool,
                GameConfig.item.ItemType.ChopTool => tool,
                GameConfig.item.ItemType.BreakTool => tool,
                GameConfig.item.ItemType.ReapTool => tool,
                GameConfig.item.ItemType.WaterTool => tool,
                GameConfig.item.ItemType.CollectTool => tool,
                GameConfig.item.ItemType.ReapableScenery => tool,
                _ => normal,
            };
            cursorEnable = true;

            //显示建造物品图片
            //if (itemDetails.itemType == ItemType.Furniture)
            //{
            //    buildImage.gameObject.SetActive(true);
            //    buildImage.sprite = itemDetails.itemOnWorldSprite;
            //    //buildImage.SetNativeSize();
            //}
        }
    }


    private void CheckCursorValid()
    {
        if(mainCamera==null)
            mainCamera = Camera.main;
        mouseWorldPos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, -mainCamera.transform.position.z));
        mouseGridPos = currentGrid.WorldToCell(mouseWorldPos);

        var playerGridPos = currentGrid.WorldToCell(PlayerTransform.position);
        //建造图片跟随移动
        //buildImage.rectTransform.position = Input.mousePosition;

        //判断在使用范围内
        if (Mathf.Abs(mouseGridPos.x - playerGridPos.x) > currentItem.ItemUseRadius || Mathf.Abs(mouseGridPos.y - playerGridPos.y) > currentItem.ItemUseRadius)
        {
            SetCursorInValid();
            return;
        }

        //Debug.Log(mouseGridPos.x+"***"+mouseGridPos.y);
        TileDetails currentTile = GridMapManager.Instance.GetTileDetailsOnMousePosition(mouseGridPos);

        if (currentTile != null)
        {
            //CropDetails currentCrop = CropManager.Instance.GetCropDetails(currentTile.seedItemID);
            //Crop crop = GridMapManager.Instance.GetCropObject(mouseWorldPos);

            //WORKFLOW:补充所有物品类型的判断
            switch (currentItem.ItemType)
            {
                case GameConfig.item.ItemType.Seed:
                    if (currentTile.sinceDuged > -1 && currentTile.seedItemID == -1&&currentTile.alreadySown==false) SetCursorValid(); else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.Commodity:
                    if (currentTile.canDropItem && currentItem.CanDropped) SetCursorValid(); else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.HoeTool:
                    if (currentTile.canDig) SetCursorValid(); else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.WaterTool:
                    if (currentTile.sinceDuged > -1) SetCursorValid(); else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.BreakTool:
                case GameConfig.item.ItemType.ChopTool:
                    //if (crop != null)
                    //{
                    //    if (crop.CanHarvest && crop.cropDetails.CheckToolAvailable(currentItem.itemID)) SetCursorValid(); else SetCursorInValid();
                    //}
                    //else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.CollectTool:
                    //if (currentCrop != null)
                    //{
                    //    if (currentCrop.CheckToolAvailable(currentItem.itemID))
                    //        if (currentTile.growthDays >= currentCrop.TotalGrowthDays) SetCursorValid(); else SetCursorInValid();
                    //    else SetCursorInValid();
                    //}
                    //else
                    //    SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.ReapTool:
                    //if (GridMapManager.Instance.HaveReapableItemsInRadius(mouseWorldPos, currentItem)) SetCursorValid(); else SetCursorInValid();
                    break;
                case GameConfig.item.ItemType.Furniture:
                    //buildImage.gameObject.SetActive(true);
                    //var bluePrintDetails = InventoryManager.Instance.bluePrintData.GetBluePrintDetails(currentItem.itemID);

                    //if (currentTile.canPlaceFurniture && InventoryManager.Instance.CheckStock(currentItem.itemID) && !HaveFurnitureInRadius(bluePrintDetails))
                    //    SetCursorValid();
                    //else
                    //    SetCursorInValid();
                    break;
            }
        }
        else
        {
            SetCursorInValid();
        }
    }

    //private bool HaveFurnitureInRadius(BluePrintDetails bluePrintDetails)
    //{
    //    var buildItem = bluePrintDetails.buildPrefab;
    //    Vector2 point = mouseWorldPos;
    //    var size = buildItem.GetComponent<BoxCollider2D>().size;

    //    var otherColl = Physics2D.OverlapBox(point, size, 0);
    //    if (otherColl != null)
    //        return otherColl.GetComponent<Furniture>();
    //    return false;
    //}
    /// <summary>
    /// 是否与UI互动
    /// </summary>
    /// <returns></returns>
    private bool InteractWithUI()
    {
        if (EventSystem.current != null && EventSystem.current.IsPointerOverGameObject())
        {
            return true;
        }
        return false;
    }
}
